package org.zjt.chapter1.io;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.oio.OioServerSocketChannel;
import io.netty.channel.socket.oio.OioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-07-12 下午5:57
 * @see
 */
@Slf4j
public class OioNetworkOperationalTest {

    public static void main(String[] args) throws InterruptedException {
        new OioNetworkOperationalTest().server();
    }

    @Test
    public void server() throws InterruptedException {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        ChannelFuture serverBindSuccess = serverBootstrap.group(new OioEventLoopGroup()).option(ChannelOption.SO_BACKLOG, 100)
                .channel(OioServerSocketChannel.class)
                .childHandler(new SimpleChannelInboundHandler<Object>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.info("server read msg:{}", msg.getClass());
                    }
                })
                .bind(9008).addListener(future -> log.info("server bind success", future.isSuccess()))
                .sync();

        serverBindSuccess.channel().closeFuture().sync();
    }

    @Test
    public void client() throws InterruptedException {
        PooledByteBufAllocator pooledByteBufAllocator = new PooledByteBufAllocator();
        ChannelFuture sync = new Bootstrap()
                .option(ChannelOption.TCP_NODELAY, true)
                .group(new OioEventLoopGroup())
                .channel(OioSocketChannel.class)
                .handler(new SimpleChannelInboundHandler<Object>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                        log.info("client read msg:{}", msg);
                    }

                    @Override
                    public void channelActive(ChannelHandlerContext ctx) throws Exception {
                        log.info("-----------channelActive----------------");
                        ByteBuf byteBuf = pooledByteBufAllocator.directBuffer();
                        byteBuf.writeBytes("hello zhang".getBytes());

                        ctx.writeAndFlush(byteBuf);
                    }
                 })
                .connect("localhost", 9008)
                .addListener(future -> log.info("client connect success", future.isSuccess()))
                .sync();

        sync.channel().closeFuture().sync();
    }

}
